package com.atguigu.grainmall.order.service.impl;

import com.atguigu.grainmall.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.grainmall.order.dao.MqMessageDao;
import com.atguigu.grainmall.order.entity.MqMessageEntity;
import com.atguigu.grainmall.order.service.MqMessageService;

@RabbitListener(queues = {"hello-java-Queue"}) // 监听 必须@EnableRabbit开启后才可以使用 在需要的方法上标注而且在容器中才能生效
@Service("mqMessageService")
public class MqMessageServiceImpl extends ServiceImpl<MqMessageDao, MqMessageEntity> implements MqMessageService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MqMessageEntity> page = this.page(
                new Query<MqMessageEntity>().getPage(params),
                new QueryWrapper<MqMessageEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 收取消息测试
     */
    @RabbitHandler // 重载接受不同队列消息
//    @RabbitListener(queues = {"hello-java-Queue"}) // 监听 必须@EnableRabbit开启后才可以使用 在需要的方法上标注而且在容器中才能生效
    public void recieveMessageTest(Message message,
                                   OrderReturnReasonEntity count,
                                   Channel channel){
        // 获取消息体
        byte[] body = message.getBody();
        // 消息头
        MessageProperties messageProperties = message.getMessageProperties();
//        System.out.println("接收到消息内容:"+message+"-->类型为:"+message.getClass());
        System.out.println("接收到消息内容:"+count+"-->类型为:"+message);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println("deliveryTag==>"+deliveryTag);
        try {
            if (deliveryTag%2 == 0){
                // 签收消息,非批量，逐个签收
                channel.basicAck(deliveryTag,false);
            }else {
                // 拒绝收货 退货
                channel.basicNack(deliveryTag,false,true);
            }
        }catch (Exception e){
            // 网络中断
        }

    }
}
